import { Injectable } from '@angular/core';

@Injectable({
    providedIn: 'root'
})
export class JiupianService {
    pi = 3.1415926535897932384626;
    a = 6378245.0;
    ee = 0.00669342162296594323;

    out_of_China(lon: number, lat: number): boolean {
        return (lon < 72.004 || lon > 137.8347 || lat < 0.8293 || lat > 55.8271);
    }

    transform_lon(x: number, y: number): number {
        let ret = 300.0 + x + 2.0 * y + 0.1 * x * x + 0.1 * x * y + 0.1 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.pi) + 20.0 * Math.sin(2.0 * x * this.pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(x * this.pi) + 40.0 * Math.sin(x / 3.0 * this.pi)) * 2.0 / 3.0;
        ret += (150.0 * Math.sin(x / 12.0 * this.pi) + 300.0 * Math.sin(x / 30.0 * this.pi)) * 2.0 / 3.0;
        return ret;
    }


    transform_lat(x: number, y: number): number {
        let ret = -100.0 + 2.0 * x + 3.0 * y + 0.2 * y * y + 0.1 * x * y + 0.2 * Math.sqrt(Math.abs(x));
        ret += (20.0 * Math.sin(6.0 * x * this.pi) + 20.0 * Math.sin(2.0 * x * this.pi)) * 2.0 / 3.0;
        ret += (20.0 * Math.sin(y * this.pi) + 40.0 * Math.sin(y / 3.0 * this.pi)) * 2.0 / 3.0;
        ret += (160.0 * Math.sin(y / 12.0 * this.pi) + 320 * Math.sin(y * this.pi / 30.0)) * 2.0 / 3.0;
        return ret;
    }

    wgs84_to_gcj02(lon: number, lat: number) {
        if (this.out_of_China(lon, lat)) {
            return {gcj_lon: lon, gcj_lat: lat};
        }

        let d_lat = this.transform_lat(lon - 105.0, lat - 35.0);
        let d_lon = this.transform_lon(lon - 105.0, lat - 35.0);
        const rad_lat = lat / 180.0 * this.pi;
        let magic = Math.sin(rad_lat);
        magic = 1 - this.ee * magic * magic;
        const sqrt_magic = Math.sqrt(magic);
        d_lat = (d_lat * 180.0) / ((this.a * (1 - this.ee)) / (magic * sqrt_magic) * this.pi);
        d_lon = (d_lon * 180.0) / (this.a / sqrt_magic * Math.cos(rad_lat) * this.pi);
        const gcj_lat = lat + d_lat;
        const gcj_lon = lon + d_lon;
        return {gcj_lon, gcj_lat};
    }

    gcj02_to_wgs84(gcj_lon: number, gcj_lat: number) {
        if (this.out_of_China(gcj_lon, gcj_lat)) {
            return {lon: gcj_lon, lat: gcj_lat};
        }

        let d_lat = this.transform_lat(gcj_lon - 105.0, gcj_lat - 35.0);
        let d_lon = this.transform_lon(gcj_lon - 105.0, gcj_lat - 35.0);
        const rad_lat = gcj_lat / 180.0 * this.pi;
        let magic = Math.sin(rad_lat);
        magic = 1 - this.ee * magic * magic;
        const sqrt_magic = Math.sqrt(magic);
        d_lat = (d_lat * 180.0) / ((this.a * (1 - this.ee)) / (magic * sqrt_magic) * this.pi);
        d_lon = (d_lon * 180.0) / (this.a / sqrt_magic * Math.cos(rad_lat) * this.pi);
        const mg_lat = gcj_lat + d_lat;
        const mg_lon = gcj_lon + d_lon;

        const lon = gcj_lon * 2 - mg_lon;
        const lat = gcj_lat * 2 - mg_lat;
        return  {lon, lat}
    }

}
